package com.nenglai.report.service;

import com.nenglai.report.Params;
import com.nenglai.report.util.WordDocxUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author kongdehui
 * @date 2021/06/21 11:03
 **/
@Slf4j
@Service
public class OutputService {

    /**
     * @param inputTpl       输入模板
     * @param outputFileName 输出文件名
     * @param params         替换参数
     * @throws IOException
     * @throws XmlException
     */
    public void output(String inputTpl, String outputFileName, Params params)
            throws IOException, XmlException {
        FileInputStream in = new FileInputStream(inputTpl);
        // 输出文件
        String output = StringUtils.hasText(params.getFilename()) ? params.getFilename() : outputFileName;
        String fileName = getOutputFilename(inputTpl, output);
        XWPFDocument doc = new XWPFDocument(in);
        // 替换段落标记
        WordDocxUtil.replaceInAllParagraphs(doc.getParagraphsIterator(), params.getParagraphs());
        // 替换表格标记
        WordDocxUtil.replaceInAllTables(doc.getTablesIterator(), params.getParagraphs());
        //

        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(fileName);
            doc.write(outStream);
            outStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                outStream.close();
            }
            in.close();
        }
    }

    /**
     * @param input          输入
     * @param outputFilename 输出模板
     * @return string
     */
    public String getOutputFilename(String input, String outputFilename) {
        String suffix = input.substring(input.lastIndexOf(".") + 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddhhmmss");
        String format = sdf.format(new Date());
        return outputFilename + "_" + format + "." + suffix;
    }
}
